package com.jar.exercise.深拷贝和浅拷贝;

import java.io.*;

/**
 * 深拷贝
 * 1、实现Serializable接口，Cloneable接口
 * 2、重写clone()方法
 */
public class Demo2 {
	public static void main(String[] args) throws CloneNotSupportedException {
		Person person = new Person();
		person.setAge(18);
		person.setName("张胜豪");
		Depart depart = new Depart();
		person.setDepart(depart);
		Person person1 = (Person) person.clone();
		System.out.println(person1 == person);
		System.out.println(person1.getDepart() == depart);
		System.out.println(person1.getAge() + "---" + person.getName());
	}
}

class Person implements Serializable, Cloneable {

	private static final long serialVersionUID = -2270298228443226508L;
	private String name;
	private int age;
	private Depart depart;

	public Depart getDepart() {
		return depart;
	}

	public void setDepart(Depart depart) {
		this.depart = depart;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public Object clone() {
		ByteArrayOutputStream bos;
		ObjectOutputStream oos = null;
		ObjectInputStream ois = null;
		try {
			bos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(bos);
			oos.writeObject(this);
			ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());

			ois = new ObjectInputStream(bis);
			return ois.readObject();
		} catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				if (oos != null) {
					oos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (ois != null) {
					ois.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}

class Depart implements Serializable {

	private static final long serialVersionUID = -5086586987595785331L;
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
